package main

import (
	"context"
	"fmt"
	"sync"
	"time"

	"github.com/marusama/cyclicbarrier"
)

func main() {
	const (
		workerCount = 4
		phases      = 3
	)

	// 创建带回调的屏障（每次突破屏障时打印阶段信息）
	barrier := cyclicbarrier.NewWithAction(workerCount, func() error {
		fmt.Println("\n=== 所有工人完成当前阶段 ===")
		return nil
	})

	var wg sync.WaitGroup
	wg.Add(workerCount)

	for i := 0; i < workerCount; i++ {
		go func(workerID int) {
			defer wg.Done()

			for phase := 1; phase <= phases; phase++ {
				// 阶段工作
				workTime := time.Duration(workerID+phase) * 200 * time.Millisecond
				fmt.Printf("工人%d 正在执行阶段%d 工作（耗时%s）\n", workerID, phase, workTime)
				time.Sleep(workTime)

				// 等待其他工人完成当前阶段
				if err := barrier.Await(context.TODO()); err != nil {
					fmt.Println("屏障等待出错:", err)
					return
				}

				// 阶段后工作
				fmt.Printf("工人%d 完成阶段%d 后续工作\n", workerID, phase)
			}
		}(i)
	}

	wg.Wait()
	fmt.Println("所有工人完成全部三个阶段的工作！")
}
